//
// Created by 后端码匠 on 2022/11/30.
//

#include <jni.h>
#include <string>

#include "libUVCCamera.h"

#include "jni_onload.h"

#define diagnosis_assert(...) assert(__VA_ARGS__)

int ret = -1;

static void localLogInit(JNIEnv *env, jclass clazz,
                         jstring logFilePath, jstring logName,
                         jint logfile_level, jint log_screen_level) {
    if (ret != 0) {
        const char *path = env->GetStringUTFChars(logFilePath, JNI_FALSE);
        const char *name = env->GetStringUTFChars(logName, JNI_FALSE);
        int fileLevel = logfile_level;
        int screenLevel = log_screen_level;
        ret = LogInit(path, name, fileLevel, screenLevel);
        env->ReleaseStringUTFChars(logFilePath, path);
        env->ReleaseStringUTFChars(logName, name);
    }
}


static void logJni(JNIEnv *env, jclass clazz, jint _level,
                   jstring _str) {
    if (ret != 0) {
        LOGE("log error! LogInit need");
        return;
    }
    const char *str = env->GetStringUTFChars(_str, JNI_FALSE);
    WriteTextLog(_level, str);
    env->ReleaseStringUTFChars(_str, str);
}

static void logClose(JNIEnv *env, jclass clazz) {
    LogClose();
    ret = -1;
}

static JNINativeMethod methods[] = {
        {"logInit",  "(Ljava/lang/String;Ljava/lang/String;II)V", (void *) localLogInit},
        {"logJni",   "(ILjava/lang/String;)V",                    (void *) logJni},
        {"logClose", "()V",                                       (void *) logClose},
};

int register_logutil(JNIEnv *env) {
    LOGV("register_logutil:");
    if (registerNativeMethods(env,
                              "com/tungkong/utils/JNILogUtils",
                              methods, NUM_ARRAY_ELEMENTS(methods)) < 0) {
        return -1;
    }
    return 0;
}

//static void nativeLogUtilsRegisterNatives(JNIEnv *jniEnv) {
//    if (jniEnv == nullptr) {
//        return;
//    }
//
//    jclass clazz = nullptr;
//    do {
//        clazz = jniEnv->FindClass("com/serenegiant/usb/JNILogUtils");
//        if (clazz == nullptr) {
//            diagnosis_assert(!"FindClass LogUtils error!");
//            break;
//        }
//        if (jniEnv->RegisterNatives(clazz, nativeUtilsMethods,
//                                    std::extent<decltype(nativeUtilsMethods)>::value) != 0) {
//            diagnosis_assert(!"RegisterNatives error!");
//            break;
//        }
//    } while (false);
//    if (jniEnv->ExceptionCheck() == JNI_TRUE) {
//        jniEnv->ExceptionClear();
//    }
//    if (clazz != nullptr) {
//        jniEnv->DeleteLocalRef(clazz);
//    }
//}